<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 160px;">
          <el-option label="进行中" value=1 />
          <el-option label="已取消" value=2 />
          <!-- <el-option label="已结束" value=3 /> -->
        </el-select>
      </el-form-item>
      <!-- 新增日期筛选 -->
      <el-form-item label="发车日期" prop="departureData">
        <el-date-picker
          v-model="queryParams.departureData"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择发车日期"
          clearable
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:date:add']"
        >新增临时车辆</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:date:edit']" 
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:date:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:date:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="发车安排" align="center" prop="scheduleId" width="300">
        <template #default="scope">
          <span>{{ getScheduleInfo(scope.row.scheduleId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发车具体日期" align="center" prop="departureData" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.departureData, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约人数" align="center" prop="reservationCount" width="100"/>
      <el-table-column label="荷载人数" align="center" prop="maxCapacit" width="100"/>

      
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status === 1 ? '进行中' : (scope.row.status === 2 ? '已取消' : '已结束') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
         <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:date:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:date:remove']">删除</el-button> -->
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['system:date:edit']">查看</el-button>  
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改日期预约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dateRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发车安排" prop="scheduleId" >
          <el-select v-model="form.scheduleId" placeholder="请选择发车安排" disabled>
            <el-option
              v-for="item in scheduleList"
              :key="item.id"
              :label="getScheduleInfo(item.id)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发车日期" prop="departureData">
          <el-date-picker clearable
            v-model="form.departureData"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发车具体日期"
            disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="荷载人数" prop="maxCapacit">
          <el-input v-model="form.maxCapacit" placeholder="请输入荷载人数" disabled/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="已取消" :value="2"></el-option>
            <el-option label="已结束" :value="3"></el-option>
            
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Date">
import { listDate, getDate, delDate, addDate, updateDate } from "@/api/busmanagement/date";
import { useRouter } from 'vue-router';
import {listSchedule} from "@/api/busmanagement/schedule"; // 导入发车安排API
import {listBus} from "@/api/busmanagement/bus"; // 导入班车管理API
import {listReservation} from "@/api/busmanagement/reservation"; // 导入预约记录API
const { proxy } = getCurrentInstance();
const router = useRouter(); // 初始化路由

const dateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const scheduleList = ref([]); // 存储发车安排列表
const busList = ref([]); // 存储班车列表

// 往返线路选项
const lineOptions = ref([
  { value: 1, label: '上午-青州---潍坊' },
  { value: 2, label: '下午-青州---潍坊' },
  { value: 3, label: '上午-潍坊---青州' },
  { value: 4, label: '下午-潍坊---青州' },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scheduleId: null,
    departureData: null,
    maxCapacit: null,
    status: null
  },
  rules: {
    status: [
      { required: true, message: "状态(1,进行中2,已取消3,已结束)不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询日期预约列表 */
async function getList() {
  loading.value = true;
  // 获取日期预约列表
  const dateResponse = await listDate(queryParams.value);
  dateList.value = dateResponse.rows;

  // 为每个日期预约项查询预约人数
  for (let i = 0; i < dateList.value.length; i++) {
    const dateItem = dateList.value[i];
    const reservationResponse = await listReservation({ dateId: dateItem.id });
    // 过滤掉reservationStatus为3的预约，只统计有效预约人数
    const validReservations = reservationResponse.rows.filter(item => item.reservationStatus !== 3);
    dateItem.reservationCount = validReservations.length; // 存储有效预约人数
  }
  total.value = dateResponse.total;

  // 获取所有发车安排列表
  const scheduleResponse = await listSchedule({ pageNum: 1, pageSize: 9999 }); // 获取所有排班数据
  scheduleList.value = scheduleResponse.rows;

  // 获取所有班车列表
  const busResponse = await listBus();
  busList.value = busResponse.rows;

  loading.value = false;
}

// 根据scheduleId获取详细信息
function getScheduleInfo(scheduleId) {
  const schedule = scheduleList.value.find(item => item.id === scheduleId);
  if (schedule) {
    const lineLabel = lineOptions.value.find(item => item.value === schedule.line)?.label;
    const bus = busList.value.find(item => item.id === schedule.busId);
    const licensePlate = bus ? bus.licensePlate : '未知车牌';
    return `车牌号: ${licensePlate}, 线路: ${lineLabel || '未知'}`;
  }
  return '无发车安排信息';
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    scheduleId: null,
    departureData: null,
    maxCapacit: null,
    createTime: null,
    updateTime: null,
    status: null
  };
  proxy.resetForm("dateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加日期预约";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDate(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改日期预约";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dateRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除日期预约编号为"' + _ids + '"的数据项？').then(function() {
    return delDate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 查看按钮操作 */
function handleView(row) {
  const _id = row.id || ids.value;
  // 跳转到预约管理页面，并传递dateId
  router.push({ path: '/CampusShuttle/reservation', query: { dateId: _id } });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('date/date/export', {
    ...queryParams.value
  }, `date_${new Date().getTime()}.xlsx`)
}

getList();
</script>
